<template>
	<view class="container">
		
		<!-- 新增分类按钮 -->
		<view class="add-section" @click="goToAddClass">
			<view class="add-icon">+</view>
			<text class="add-text">新增分类</text>
		</view>
		
		<!-- 已有分类标题 -->
		<view class="existing-title">
			<text class="title-text">已有商品分类</text>
			<view class="sort-section" @click="toggleSort">
				<text class="sort-icon">⇅</text>
				<text class="sort-text">排序</text>
			</view>
		</view>
		
		<!-- 分类列表 -->
		<view class="category-list">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 空状态 -->
			<view v-else-if="flatCategories.length === 0" class="empty-container">
				<text class="empty-text">暂无分类数据</text>
			</view>
			
			<!-- 分类树形列表 -->
			<template v-else>
				<view
					v-for="node in flatTreeList"
					:key="node.id"
					class="category-item"
					:class="{ 
						'moving': movingCategoryId === node.id,
						'moving-up': movingCategoryId === node.id && movingDirection === 'up',
						'moving-down': movingCategoryId === node.id && movingDirection === 'down'
					}"
					:style="{ paddingLeft: (node.level * 20) + 'px' }"
				>
					<view class="category-content">
						<view 
							v-if="node.children && node.children.length > 0"
							class="expand-icon"
							@click.stop="toggleExpand(node.id)"
						>
							<text class="expand-arrow" :class="{ expanded: expandedCategories[node.id] }">▶</text>
						</view>
						<view v-else class="expand-placeholder"></view>
						<text class="category-name">{{ node.name }}</text>
					</view>
					<view class="sort-controls">
						<view 
							class="sort-btn add-child-btn" 
							@click.stop="goToAddChildClass(node.id)"
						>
							<text class="sort-arrow add-arrow">+</text>
						</view>
						<view class="divider"></view>
						<view 
							class="sort-btn" 
							:class="{ disabled: node.isFirst }"
							@click.stop="handleMoveUp(node.category, node.siblings, node.index)"
						>
							<text class="sort-arrow">↑</text>
						</view>
						<view class="divider"></view>
						<view 
							class="sort-btn downSort" 
							:class="{ disabled: node.isLast }"
							@click.stop="handleMoveDown(node.category, node.siblings, node.index)"
						>
							<text class="sort-arrow downArrow">↓</text>
						</view>
						<view class="divider"></view>
						<view 
							class="sort-btn delete-btn" 
							@click.stop="deleteCategory(node.id)"
						>
							<text class="sort-arrow delete-arrow">×</text>
						</view>
					</view>
				</view>
			</template>
		</view>
		
		<!-- 底部指示器 -->
		<view class="home-indicator"></view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			categories: [], // 树形结构的分类数据
			flatCategories: [], // 扁平化的分类数据（用于空状态判断）
			loading: false,
			movingCategoryId: null, // 正在移动的分类ID，用于动画效果
			movingDirection: '', // 移动方向：'up' 或 'down'
			expandedCategories: {} // 展开状态：{ categoryId: true/false }
		}
	},
	computed: {
		// 扁平化的树形列表（根据展开状态）
		flatTreeList() {
			return this.renderTree(this.categories, 0)
		}
	},
	onLoad() {
		// 页面初始化，不在这里加载数据，统一在 onShow 中加载
	},
	onShow() {
		// 页面显示时加载数据（包括首次进入和从其他页面返回）
		this.loadCategories()
	},
	methods: {
		// 加载分类列表
		loadCategories() {
			this.loading = true
			
			// 使用新的 treeData 接口，返回的已经是树形结构
			this.$u.api.productCategory.treeData().then(res => {
				this.loading = false
				
				if (res && Array.isArray(res) && res.length > 0) {
					// treeData 接口直接返回树形结构数组
					this.categories = res || []
					// 扁平化数据用于统计和传递
					this.flatCategories = this.flattenTree(res)
				} else if (res && res.list && res.list.length > 0) {
					// 兼容旧接口格式
					this.flatCategories = res.list || []
					this.categories = this.buildTree(res.list || [])
				} else {
					this.categories = []
					this.flatCategories = []
				}
			}).catch(err => {
				this.loading = false
				console.error('获取分类列表失败:', err)
				uni.showToast({
					title: '获取分类列表失败',
					icon: 'none'
				})
			})
		},
		
		// 将树形结构扁平化（用于统计和传递）
		flattenTree(tree, result = []) {
			tree.forEach(node => {
				result.push({
					id: node.id,
					name: node.name,
					parentCode: node.parentCode || '0',
					sort: node.sort,
					status: node.status
				})
				if (node.children && node.children.length > 0) {
					this.flattenTree(node.children, result)
				}
			})
			return result
		},
		
		// 将扁平数据转换为树形结构（兼容旧接口）
		buildTree(list) {
			// 创建ID映射表
			const map = {}
			list.forEach(item => {
				item.children = []
				map[item.id] = item
			})
			
			// 构建树形结构
			const tree = []
			list.forEach(item => {
				const parentCode = item.parentCode || item.parentId || item.parent_id || '0'
				
				if (parentCode === '0' || parentCode === 0 || !parentCode) {
					// 顶级分类
					tree.push(item)
				} else {
					// 子分类
					const parent = map[parentCode]
					if (parent) {
						if (!parent.children) {
							parent.children = []
						}
						parent.children.push(item)
					} else {
						// 如果找不到父分类，当作顶级分类处理
						tree.push(item)
					}
				}
			})
			
			// 递归排序（按sort字段）
			const sortTree = (nodes) => {
				nodes.sort((a, b) => {
					const sortA = a.sort || a.sortNo || 0
					const sortB = b.sort || b.sortNo || 0
					return sortA - sortB
				})
				nodes.forEach(node => {
					if (node.children && node.children.length > 0) {
						sortTree(node.children)
					}
				})
			}
			
			sortTree(tree)
			return tree
		},
		
		// 切换展开/折叠
		toggleExpand(categoryId) {
			this.$set(this.expandedCategories, categoryId, !this.expandedCategories[categoryId])
		},
		
		// 递归渲染树形结构为扁平列表（根据展开状态）
		renderTree(nodes, level) {
			const result = []
			if (!nodes || nodes.length === 0) {
				return result
			}
			
			nodes.forEach((node, index) => {
				// 同级兄弟节点就是 nodes 数组本身
				const siblings = nodes
				const isFirst = index === 0
				const isLast = index === siblings.length - 1
				
				result.push({
					id: node.id,
					name: node.name,
					category: node,
					level: level,
					index: index,
					siblings: siblings,
					children: node.children,
					isFirst: isFirst,
					isLast: isLast
				})
				
				// 如果有子节点且已展开，递归渲染子节点
				if (node.children && node.children.length > 0 && this.expandedCategories[node.id]) {
					result.push(...this.renderTree(node.children, level + 1))
				}
			})
			return result
		},
		
		// 在树中查找节点
		findNodeById(nodes, nodeId) {
			for (const node of nodes) {
				if (node.id === nodeId) {
					return node
				}
				if (node.children && node.children.length > 0) {
					const found = this.findNodeById(node.children, nodeId)
					if (found) {
						return found
					}
				}
			}
			return null
		},
		
		// 根据 parentCode 查找同级兄弟节点（兼容旧逻辑）
		findSiblingsByParentCode(nodes, parentCode, result = []) {
			nodes.forEach(node => {
				const nodeParentCode = node.parentCode || node.parentId || node.parent_id || '0'
				if (nodeParentCode === parentCode || (parentCode === '0' && !nodeParentCode)) {
					result.push(node)
				}
				if (node.children && node.children.length > 0) {
					this.findSiblingsByParentCode(node.children, parentCode, result)
				}
			})
			return result
		},
		
		// 查找分类在树中的位置
		findCategoryInTree(tree, categoryId, path = []) {
			for (let i = 0; i < tree.length; i++) {
				const node = tree[i]
				if (node.id === categoryId) {
					return { node, index: i, siblings: tree, path }
				}
				if (node.children && node.children.length > 0) {
					const found = this.findCategoryInTree(node.children, categoryId, [...path, i])
					if (found) {
						return found
					}
				}
			}
			return null
		},
		
		// 处理上移
		handleMoveUp(category, siblings, index) {
			if (index <= 0) {
				return
			}
			
			// 标记正在移动的分类和方向，触发动画
			this.movingCategoryId = category.id
			this.movingDirection = 'up'
			
			// 延迟执行交换，让动画播放到一半
			setTimeout(() => {
				// 交换位置
				const temp = siblings[index]
				this.$set(siblings, index, siblings[index - 1])
				this.$set(siblings, index - 1, temp)
				
				// 强制更新视图
				this.$forceUpdate()
			}, 200)
			
			this.changeSort(1, category.id)
			
			// 动画结束后清除标记
			setTimeout(() => {
				this.movingCategoryId = null
				this.movingDirection = ''
			}, 400)
		},
		
		// 处理下移
		handleMoveDown(category, siblings, index) {
			if (index < 0 || index >= siblings.length - 1) {
				return
			}
			
			// 标记正在移动的分类和方向，触发动画
			this.movingCategoryId = category.id
			this.movingDirection = 'down'
			
			// 延迟执行交换，让动画播放到一半
			setTimeout(() => {
				// 交换位置
				const temp = siblings[index]
				this.$set(siblings, index, siblings[index + 1])
				this.$set(siblings, index + 1, temp)
				
				// 强制更新视图
				this.$forceUpdate()
			}, 200)
			
			this.changeSort(-1, category.id)
			
			// 动画结束后清除标记
			setTimeout(() => {
				this.movingCategoryId = null
				this.movingDirection = ''
			}, 400)
		},
		
		changeSort(type, id) {
			this.$u.api.productCategory.changeSort({direction: type, id: id}).then(res => {
				if (res && res.result === 'true') {
					uni.showToast({
						title: type == 1 ? '上移成功' : '下移成功',
						icon: 'success'
					})
				} else {
					uni.showToast({
						title: res.message || '排序失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				console.error('排序失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			})
		},
		
		goToAddClass() {
			// 传递分类树数据，用于选择父分类（不传递parentId，表示顶级分类）
			uni.navigateTo({
				url: '/pages/inventoryManagement/addClass?categories=' + encodeURIComponent(JSON.stringify(this.flatCategories))
			})
		},
		
		// 跳转到新增子分类页面，并自动选中当前分类作为父分类
		goToAddChildClass(parentId) {
			// 传递分类数据和父分类ID
			uni.navigateTo({
				url: '/pages/inventoryManagement/addClass?categories=' + encodeURIComponent(JSON.stringify(this.flatCategories)) + '&parentId=' + encodeURIComponent(parentId)
			})
		},
		
		toggleSort() {
			// 排序功能
			console.log('切换排序')
		},
		
		// 删除分类
		deleteCategory(categoryId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个分类吗？删除后不可恢复！',
				success: (res) => {
					if (res.confirm) {
						this.confirmDelete(categoryId)
					}
				}
			})
		},
		
		// 确认删除分类
		confirmDelete(categoryId) {
			uni.showLoading({ title: '删除中...' })
			
			const params = {
				id: categoryId
			}
			
			this.$u.api.productCategory.delete(params).then(res => {
				uni.hideLoading()
				
				if (res && res.result === 'true') {
					uni.showToast({
						title: res.message || '删除成功',
						icon: 'success'
					})
					
					// 重新加载分类列表
					this.loadCategories()
				} else {
					uni.showToast({
						title: res.message || '删除失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('删除分类失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			})
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	position: relative;
}


/* 新增分类区域 */
.add-section {
	display: flex;
	align-items: center;
	padding: 20px;
	gap: 10px;
}

.add-icon {
	width: 30px;
	height: 30px;
	border: 2px solid #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #ff4069;
	font-size: 18px;
	font-weight: bold;
}

.add-text {
	color: #ff4069;
	font-size: 16px;
	font-weight: 500;
}

/* 已有分类标题 */
.existing-title {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 20px 15px;
}

.title-text {
	color: #999999;
	font-size: 14px;
}

.sort-section {
	display: flex;
	align-items: center;
	gap: 5px;
}

.sort-icon {
	color: #ff4069;
	font-size: 16px;
}

.sort-text {
	color: #ff4069;
	font-size: 14px;
}

/* 分类列表 */
.category-list {
	padding: 0 20px;
}

.category-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f5f5f5;
	position: relative;
}

.category-content {
	display: flex;
	align-items: center;
	flex: 1;
	gap: 8px;
}

.expand-icon {
	width: 20px;
	height: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.expand-arrow {
	color: #999999;
	font-size: 12px;
	transition: transform 0.2s ease;
}

.expand-arrow.expanded {
	transform: rotate(90deg);
}

.expand-placeholder {
	width: 20px;
	height: 20px;
}

.children-container {
	overflow: hidden;
}

/* 移动动画效果 */
.category-item.moving {
	z-index: 10;
}

/* 上移动画 - 平滑向上移动 */
.category-item.moving-up {
	animation: moveUp 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 下移动画 - 平滑向下移动 */
.category-item.moving-down {
	animation: moveDown 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes moveUp {
	0% {
		transform: translateY(0);
		background-color: #ffffff;
		box-shadow: none;
	}
	50% {
		transform: translateY(-50px);
		background-color: #fff8fa;
		box-shadow: 0 4px 12px rgba(255, 64, 105, 0.2);
	}
	100% {
		transform: translateY(0);
		background-color: #ffffff;
		box-shadow: none;
	}
}

@keyframes moveDown {
	0% {
		transform: translateY(0);
		background-color: #ffffff;
		box-shadow: none;
	}
	50% {
		transform: translateY(50px);
		background-color: #fff8fa;
		box-shadow: 0 4px 12px rgba(255, 64, 105, 0.2);
	}
	100% {
		transform: translateY(0);
		background-color: #ffffff;
		box-shadow: none;
	}
}

.category-name {
	color: #333333;
	font-size: 14px;
}

.sort-controls {
	display: flex;
	align-items: center;
	gap: 10px;
}

.sort-btn {
	width: 20px;
	height: 20px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 2px solid #ff4069;
	transition: all 0.2s ease;
}

.sort-btn:active:not(.disabled) {
	transform: scale(0.9);
	background-color: #ff4069;
}

.sort-btn:active:not(.disabled) .sort-arrow {
	color: #ffffff;
}

.downSort{
   border: 2px solid #000;
   color: #000;
}

.downSort:active:not(.disabled) {
	background-color: #000;
}

.downSort:active:not(.disabled) .sort-arrow {
	color: #ffffff;
}

.sort-btn.disabled {
	border: 2px solid #E8E8E8;
}

.sort-arrow {
	color: #ff4069;
	font-size: 12px;
	font-weight: bold;
}

.downArrow{
	color: #000;
}

.add-child-btn {
	border: 2px solid #ff4069;
}

.add-child-btn:active {
	background-color: #ff4069;
	transform: scale(0.9);
}

.add-child-btn:active .add-arrow {
	color: #ffffff;
}

.add-arrow {
	color: #ff4069;
	font-size: 14px;
	font-weight: bold;
}

.delete-btn {
	border: 2px solid #ff4757;
}

.delete-btn:active {
	background-color: #ff4757;
	transform: scale(0.9);
}

.delete-btn:active .delete-arrow {
	color: #ffffff;
}

.delete-arrow {
	color: #ff4757;
}

.sort-btn.disabled .sort-arrow {
	color: #E8E8E8;
}

.divider {
	width: 1px;
	height: 20px;
	background-color: #e0e0e0;
}

/* 加载状态 */
.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40px 0;
}

.loading-text {
	color: #999999;
	font-size: 14px;
}

/* 空状态 */
.empty-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40px 0;
}

.empty-text {
	color: #999999;
	font-size: 14px;
}

/* 底部指示器 */
.home-indicator {
	position: fixed;
	bottom: 10px;
	left: 50%;
	transform: translateX(-50%);
	width: 40px;
	height: 4px;
	background-color: #000000;
	border-radius: 2px;
}
</style>
